package com.zhou.essearch.controller;

import cn.hutool.core.date.DateUtil;
import com.zhou.essearch.document.EsLog;
import com.zhou.essearch.repository.EsLogDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.cluster.ClusterHealth;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/es")
public class EsLogController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private EsLogDao logDao;

    @GetMapping("/getEsInfo")
    public ClusterHealth getEsInfo() {
        return elasticsearchRestTemplate.cluster().health();
    }

    @PostMapping("/save")
    public EsLog save() {
        EsLog log = new EsLog();
        return logDao.save(log);
    }

    @GetMapping("/findOne/{id}")
    public EsLog findOne(@PathVariable("id") String id) {
        return logDao.findById(id).get();
    }

    @GetMapping("/findPage")
    public SearchHits<EsLog> findPage() {

        Long start = DateUtil.parse("2021-09-21 21:00:00").getTime();
        Long end = DateUtil.endOfDay(DateUtil.parse("2021-09-26 22:00:00")).getTime();

        Pageable pageable = PageRequest.of(0, 2, Sort.by(Sort.Direction.DESC, "createTime"));

//        CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("name").is("查询"));
        CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria());
        criteriaQuery.addCriteria(new Criteria("timeMillis").between(start, end));
        criteriaQuery.setPageable(pageable);

        SearchHits<EsLog> searchHits = elasticsearchRestTemplate.search(criteriaQuery, EsLog.class);
        return searchHits;
    }
}
